#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

int tickets = 10;

// 条件变量必须配合互斥锁使用
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* start_routine(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        // 暂时省略条件判断
        std::cout << name << " -> " << tickets-- << std::endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
#define NUM 5
    // 通过条件变量控制线程的执行
    pthread_t t[NUM];
    for(int i = 0; i < NUM; ++i)
    {
        // 这样写和下面写有什么不同
        // char nameBuffer[64];
        // snprintf(nameBuffer, sizeof(nameBuffer) - 1, "thread_%d", i+1);
        // pthread_create(t+i, nullptr, start_routine, nameBuffer);

        char* name = new char[64];
        snprintf(name, 64, "thread_%d", i + 1);
        pthread_create(t+i, nullptr, start_routine, name);

        // delete name;
    }

    while(true)
    {
        sleep(1);
        pthread_cond_signal(&cond);// 唤起条件变量cond中的一个等待线程
        // pthread_cond_broadcast(&cond);// 唤醒条件变量cond中的所有等待线程
        std:: cout << "main thread wakeup one thread ..." << std::endl;
    }

    for(const auto tid : t)
    {
        pthread_join(tid, nullptr);
    }

    return 0;
}